﻿@using System.Configuration
@using System.Data.SqlClient
@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Claims Status Page";

    bool hasError = false;
    string errorMessage = string.Empty;
    bool hasSuccess = false;
    string successMessage = string.Empty;

    string frm_filter_entryowner = string.Empty;
    string frm_filter_claimdate = string.Empty;
    string frm_filter_entries = string.Empty;
    string sql_filter = string.Empty;
    string where_clause = string.Empty;
    string frm_filter_claimstartdate = string.Empty;
    string frm_filter_claimenddate = string.Empty;
    string frm_filter_claimstatus = string.Empty;
    DateTime tempDate;

    List<KeppelLand.Entities.Claimant> claimantList = null;
    List<KeppelLand.Entities.Claim> claimList = null;
    KeppelLand.Entities.ClaimSummary claimSummary = null;
    
    System.Data.DataSet ds = new System.Data.DataSet("CurrentClaims");

    if (IsPost)
    {
        if (Request.Form["actionButton"] == "filter")
        {
            frm_filter_entries = Request.Form["filter_entries"];
            string[] entries = frm_filter_entries.Split(',');
            if (entries.Length > 0)
            {
                frm_filter_entries = "[";
                foreach (string en in entries)
                {
                    frm_filter_entries = frm_filter_entries + "'" + en + "',";

                    if (!string.IsNullOrEmpty(en.Trim()))
                    {
                        sql_filter = sql_filter + string.Format("{0},", en.Trim());
                    }
                }
                frm_filter_entries = frm_filter_entries.Remove(frm_filter_entries.Length - 1, 1);
                frm_filter_entries = frm_filter_entries + "]";
                if (sql_filter.Length > 0)
                {
                    sql_filter = sql_filter.Remove(sql_filter.Length - 1, 1);
                }
            }

            if (!string.IsNullOrEmpty(Request.Form["claimStartDate"]))
            {
                frm_filter_claimstartdate = Request.Form["claimStartDate"].Trim();
                if (DateTime.TryParseExact(Request.Form["claimStartDate"].Trim(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out tempDate))
                {
                    where_clause = where_clause + string.Format(" AND ClaimDate >= '{0}' ", tempDate.ToString("yyyy-MM-dd"));
                }
            }
            if (!string.IsNullOrEmpty(Request.Form["claimEndDate"]))
            {

                frm_filter_claimenddate = Request.Form["claimEndDate"].Trim();

                if (DateTime.TryParseExact(Request.Form["claimEndDate"].Trim(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out tempDate))
                {
                    where_clause = where_clause + string.Format(" AND ClaimDate <= '{0}' ", tempDate.ToString("yyyy-MM-dd"));
                }
            }
            if (!string.IsNullOrEmpty(Request.Form["claimStatus"]))
            {
                frm_filter_claimstatus = Request.Form["claimStatus"].Trim();
                switch (frm_filter_claimstatus.ToUpperInvariant())
                {
                    case "A":
                        where_clause = where_clause + " AND Status = 0 ";
                        break;
                    case "B":
                        where_clause = where_clause + " AND (Status = 1) ";
                        break;
                    case "C":
                        where_clause = where_clause + " AND (Status = 3) ";
                        break;
                    case "D":
                        where_clause = where_clause + " AND (Status = 5 OR Status = 6) ";
                        break;
                }
            }
        } // if (Request.Form["actionButton"] == "filter")

        if (Request.Form["actionButton"] == "reject")
        {
            frm_filter_entries = Request.Form["filter_entries"];
            string[] entries = frm_filter_entries.Split(',');
            if (entries.Length > 0)
            {
                frm_filter_entries = "[";
                foreach (string en in entries)
                {
                    frm_filter_entries = frm_filter_entries + "'" + en + "',";

                    if (!string.IsNullOrEmpty(en.Trim()))
                    {
                        sql_filter = sql_filter + string.Format("{0},", en.Trim());
                    }
                }
                frm_filter_entries = frm_filter_entries.Remove(frm_filter_entries.Length - 1, 1);
                frm_filter_entries = frm_filter_entries + "]";
                if (sql_filter.Length > 0)
                {
                    sql_filter = sql_filter.Remove(sql_filter.Length - 1, 1);
                }
            }

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EOCS"].ConnectionString))
            {
                System.Data.DataSet dsRejectedClaims = new System.Data.DataSet("RejectedClaims");
                System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
                System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd);
                cmd.CommandText = @"SELECT * FROM Claim WHERE Status = 1 AND Id IN (SELECT data FROM dbo.fnSplitString(@IdList,','));";
                cmd.Parameters.AddWithValue("@IdList", Request.Form["selected_id"]);

                conn.Open();

                da.Fill(dsRejectedClaims, "RejectedClaims");

                cmd.CommandText = @"SELECT * FROM B2E WHERE EmployeeMaster IN (
        SELECT DISTINCT RecommenderId   FROM Claim WHERE Status = 1 AND Id IN (SELECT data FROM dbo.fnSplitString(@IdList,',')) AND RecommenderId   IS NOT NULL
UNION   SELECT DISTINCT ApproverId      FROM Claim WHERE Status = 1 AND Id IN (SELECT data FROM dbo.fnSplitString(@IdList,',')) AND ApproverId      IS NOT NULL
);";
                da.Fill(dsRejectedClaims, "RecommenderAndApprover");

                string emailBody = KeppelLand.Controllers.ClaimController.RejectClaimEmailContent(
                    dsRejectedClaims.Tables["RejectedClaims"],
                    Request.Form["rejection_reason"],
                    KeppelLand.Helpers.TranslationHelper.GetNameLegalByDomainName(
                    KeppelLand.Helpers.UserIdentityHelper.GetHRName()));

                cmd.CommandText = @"UPDATE Claim SET Status = @NewStatus, RecommenderId = NULL, RecommendDate = NULL, ApproverId = NULL, ApproveDate = NULL, RejectorId = @EmployeeMaster, RejectDate = @RejectDate, RejectReason = @RejectReason
WHERE Status = @CurrentStatus
AND Id IN (SELECT data FROM dbo.fnSplitString(@IdList,','));";
                cmd.Parameters.AddWithValue("@NewStatus", KeppelLand.Entities.ClaimStatus.DRAFT);
                cmd.Parameters.AddWithValue("@EmployeeMaster", KeppelLand.Helpers.TranslationHelper.GetEmployeeMasterByDomainName(
                    KeppelLand.Helpers.UserIdentityHelper.GetHRName()));
                cmd.Parameters.AddWithValue("@RejectDate", KeppelLand.Helpers.UserIdentityHelper.GetInputDate());
                cmd.Parameters.AddWithValue("@RejectReason", Request.Form["rejection_reason"]);
                cmd.Parameters.AddWithValue("@CurrentStatus", KeppelLand.Entities.ClaimStatus.SUBMITTED_TO_HR);
                cmd.ExecuteNonQuery();

                // Send rejection e-mail
                foreach (System.Data.DataRow recipientRows in dsRejectedClaims.Tables["RecommenderAndApprover"].Rows)
                {
                    KeppelLand.Helpers.EmailHelper.SendEmail(
                        recipientRows["Email"].ToString(), "Overtime claims rejected by HR", emailBody, true);
                }

                hasSuccess = true;
                successMessage = "Claim(s) are rejected.";
            }
        } // if (Request.Form["actionButton"] == "reject")

        if (Request.Form["actionButton"] == "download")
        {
            frm_filter_entries = Request.Form["download_filter_entries"];
            string[] entries = frm_filter_entries.Split(',');
            if (entries.Length > 0)
            {
                frm_filter_entries = "[";
                foreach (string en in entries)
                {
                    frm_filter_entries = frm_filter_entries + "'" + en + "',";

                    if (!string.IsNullOrEmpty(en.Trim()))
                    {
                        sql_filter = sql_filter + string.Format("{0},", en.Trim());
                    }
                }
                frm_filter_entries = frm_filter_entries.Remove(frm_filter_entries.Length - 1, 1);
                frm_filter_entries = frm_filter_entries + "]";
                if (sql_filter.Length > 0)
                {
                    sql_filter = sql_filter.Remove(sql_filter.Length - 1, 1);
                }
            }
            
            byte[] fileBytes = KeppelLand.Controllers.ReportController.GetClaimsSubmittedToHRReport(
                Request.Form["download_format"],
                KeppelLand.Helpers.UserIdentityHelper.GetClaimantName(),
                sql_filter);
            Response.Clear();
            Response.ContentType = KeppelLand.Helpers.TranslationHelper.GetContentType(Request.Form["download_format"]);
            Response.AddHeader("content-disposition", "attachment; filename=" + KeppelLand.Helpers.TranslationHelper.GetFileName(Request.Form["download_format"], "Claims"));
            Response.BinaryWrite(fileBytes);
            Response.Flush();
            Response.End();
        } // if (Request.Form["actionButton"] == "download")

    } // if (IsPost)

    //claimantList = KeppelLand.Controllers.ClaimController.GetClaimantListSubmittedToHR();
    //claimList = KeppelLand.Controllers.ClaimController.GetClaimListSubmittedToHR(sql_filter);
    //claimSummary = KeppelLand.Controllers.ClaimController.GetClaimSummarySubmittedToHR(
    //    KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName(), sql_filter);

    //claimantList = KeppelLand.Controllers.ClaimController.GetAllClaimantList();
    //claimList = KeppelLand.Controllers.ClaimController.GetAllClaimListSubmitted(sql_filter);
    //claimSummary = KeppelLand.Controllers.ClaimController.GetAllClaimSummarySubmitted(
    //    KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName(), sql_filter);

    bool isSecretary = KeppelLand.Controllers.B2EController.IsSecretary(KeppelLand.Helpers.UserIdentityHelper.GetSecretaryName());
    
    if (isSecretary)
    {
        string b2e_section = KeppelLand.Controllers.B2EController.GetSection(KeppelLand.Helpers.UserIdentityHelper.GetSecretaryName());
        claimantList = KeppelLand.Controllers.ClaimController.GetAllClaimantInSectionList(b2e_section, where_clause);
        claimList = KeppelLand.Controllers.ClaimController.GetAllClaimListSubmittedInSection(sql_filter, b2e_section, where_clause);
        claimSummary = KeppelLand.Controllers.ClaimController.GetAllClaimSummarySubmittedInSection(
            KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName(), sql_filter, b2e_section, where_clause);
    }
    else
    {
        claimantList = KeppelLand.Controllers.ClaimController.GetAllClaimantList(where_clause);
        claimList = KeppelLand.Controllers.ClaimController.GetAllClaimListSubmitted(sql_filter, where_clause);
        claimSummary = KeppelLand.Controllers.ClaimController.GetAllClaimSummarySubmitted(
            KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName(), sql_filter, where_clause);
    }
}

@if (!KeppelLand.Helpers.UserIdentityHelper.IsTrainer())
{
    @RenderPage("~/Shared/Access_Control.cshtml");
    return;
}

<div class="container-fluid main-content" role="main">

    @RenderPage("~/Shared/Help_Tab.cshtml")

    @if (hasError)
    {
        <div class="alert alert-danger alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            @Html.Raw(errorMessage)
        </div>
    }
    @if (hasSuccess)
    {
        <div class="alert alert-success alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            @successMessage
        </div>
    }

    <h2>
        Claims Status
        @if (KeppelLand.Helpers.UserIdentityHelper.IsSimulatingHR())
        {
            <text>(simulating @DisplayHelper.LegalName(KeppelLand.Helpers.UserIdentityHelper.GetHRName()))</text>
        }
        @if (KeppelLand.Helpers.UserIdentityHelper.IsTraining())
        {
            <text>(training mode)</text>
        }
    </h2>

    <form method="post" id="filter_form">

        <table class="table table-striped table-bordered">
            <tbody>
                <tr>
                    <th class="col-lg-2" style="vertical-align:middle;">
                        User Filter</th>
                    <td class="col-lg-10">
                        <select id="filter_entryowner">
                            <option value="">All</option>
                            @foreach (KeppelLand.Entities.Claimant claimant in claimantList)
                            {
                                <option value="@claimant.EmployeeMaster">@DisplayHelper.LegalNameByEmployeeMaster(claimant.EmployeeMaster)</option>
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <th class="col-lg-2" style="vertical-align:middle;">
                        B2E ID Filter
                    </th>
                    <td class="col-lg-10">
                        <select id="filter_b2eId">
                            <option value="">All</option>
                            @foreach (KeppelLand.Entities.Claimant claimant in claimantList)
                            {
                                <option value="@claimant.EmployeeMaster">@claimant.EmployeeMaster</option>
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <th class="col-lg-2" style="vertical-align:middle;">
                        Date Filter
                    </th>
                    <td class="col-lg-10">
                        <label>Start Date</label>
                        <input type="date" class="datepicker" name="claimStartDate" id="claimStartDate" style="width:116px;" value="@frm_filter_claimstartdate" autocomplete="off" />
                        &nbsp;&nbsp;
                        <label>End Date</label>
                        <input type="date" class="datepicker" name="claimEndDate" id="claimEndDate" style="width:116px;" value="@frm_filter_claimenddate" autocomplete="off" />
                    </td>
                    <td rowspan="2" style="vertical-align:middle">
                        <button type="button" class="btn btn-primary" name="filterButton" id="filterButton">Refresh</button>
                    </td>
                </tr>
                <tr>
                    <th class="col-lg-2" style="vertical-align:middle;">
                        Status Filter
                    </th>
                    <td class="col-lg-10">
                        <select name="claimStatus" id="claimStatus">
                            <option value="" @DisplayHelper.AddSelectedAttribute(frm_filter_claimstatus == "")>All Status</option>
                            <option value="A" @DisplayHelper.AddSelectedAttribute(frm_filter_claimstatus == "A")>Pending Submission</option>
                            <option value="B" @DisplayHelper.AddSelectedAttribute(frm_filter_claimstatus == "B")>Pending Approval 1</option>
                            <option value="C" @DisplayHelper.AddSelectedAttribute(frm_filter_claimstatus == "C")>Pending Approval 2</option>
                            <option value="D" @DisplayHelper.AddSelectedAttribute(frm_filter_claimstatus == "D")>Processed(HR)</option>
                        </select>

                    </td>
                </tr>
            </tbody>
        </table>

        <input type="hidden" name="filter_entries" id="filter_entries" />
        <input type="hidden" name="actionButton" id="filter_form_action" />
    </form>

    
    @*@RenderPage("~/Shared/Claims_History.cshtml", claimList, claimSummary)*@

    @RenderPage("~/Shared/Employee_Claim_History.cshtml", claimList, claimSummary)

    @*@RenderPage("~/Shared/Reject_Claims_Secretary.cshtml", claimList, claimSummary)*@
    

</div>

@RenderPage("~/Shared/Standard_Modals.cshtml")

<div class="modal fade" id="rejectionModal" tabindex="-1" role="dialog" aria-labelledby="rejectionModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="rejectionModalLabel">Reject Claim(s)</h4>
            </div>
            <div class="modal-body">

                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Instructions</h3>
                    </div>
                    <div class="panel-body">
                        <ol>
                            <li>Enter your reasons for rejecting the claim(s).</li>
                            <li>Click Reject button to reject claims back to claimant.</li>
                            <li>Click Cancel button to close this dialog.</li>
                        </ol>
                    </div>
                </div>

                <label for="">Reason(s) for rejection of claims:</label>

                <textarea class="form-control" id="rejection_reason_entry" rows="12"></textarea>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="rejectionModal_OK">
                    <span class="glyphicon glyphicon-send" aria-hidden="true"></span> Reject
                </button>
                <button type="button" class="btn btn-primary" id="rejectionModal_Cancel" data-dismiss="modal">
                    <span class="glyphicon glyphicon-stop" aria-hidden="true"></span> Cancel
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="helpModal" tabindex="-1" role="dialog" aria-labelledby="helpModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="helpModalLabel">Help <small>(Reject Claim)</small></h4>
            </div>
            <div class="modal-body">
                <p>
                    HR users should use this page to reject claim(s).
                </p>

                <div class="panel panel-default">
                    <div class="panel-heading">Instructions</div>
                    <div class="panel-body">
                        <p>
                            This page is for HR users to reject claims that should not be claimable by user.<br />
                        </p>

                        <ul>
                            <li>HR can click on reject button on the corresponding row to reject that claim.</li>
                            <li>If there are too many entries, user can search for the entry based on username and date and then perform the above step.</li>

                            <li>If there are no claims pending submission, page should indicate as such</li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="helpModal_Close" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

@section Scripts
{
    <script type="text/javascript" src="~/Scripts/kendo/2014.3.1119/kendo.ui.core.min.js"></script>
    <script type="text/javascript" src="~/Scripts/moment.js"></script>
    <script type="text/javascript" src="~/Scripts/moment-with-locales.js"></script>
    <script type="text/javascript" src="~/Scripts/qTip/jquery.qtip.js"></script>
    <script type="text/javascript">
    function download(format) {
        $("#approval_form #actionButton").val("download");
        $("#approval_form #download_format").val(format);
        $("#approval_form #download_filter_entries").val($("#filter_entryowner").data("kendoMultiSelect").value());
        $("#approval_form").submit();
    }

    (function ($) {
        "use strict";
        $(document).ready(function () {

            var optionsDate, ctlClaimStartDate, ctlClaimEndDate;

            optionsDate = {
                format: "dd/MM/yyyy",
                parseFormats: [
                "dd/MMMM/yyyy",
                "dd-MMMMyyyy",
                "dd/MM/yyyy",
                "dd-MM-yyyy",
                "ddMMyyyy",
                "ddMMyy",
                "ddMM"
                ],
                change: function () { }
            }; // optionsDate = {

            ctlClaimStartDate = $("#claimStartDate").kendoDatePicker(optionsDate);
            ctlClaimEndDate = $("#claimEndDate").kendoDatePicker(optionsDate);

            // Add tooltip to table
            $('#approvable_claims tbody td').qtip({
                position: {
                    my: 'top center',  // Position my top left...
                    at: 'bottom center' // at the bottom right of...
                }
            });

            var multi = $("#filter_entryowner").kendoMultiSelect({
                change: function (e) {
                    $("#filter_entries").val(this.value());
                    $("#filter_form_action").val("filter");
                    $("#filter_form").submit();
                }
            }).data("kendoMultiSelect");
            multi.value(@Html.Raw(frm_filter_entries));

            var multi2 = $("#filter_b2eId").kendoMultiSelect({
                change: function (e) {
                    $("#filter_entries").val(this.value());
                    $("#filter_form_action").val("filter");
                    $("#filter_form").submit();
                }
            }).data("kendoMultiSelect");
            multi2.value(@Html.Raw(frm_filter_entries));

            $("#filterButton").click(function () {

                var multiselect = $("#filter_entryowner").data("kendoMultiSelect");
                $("#filter_entries").val(multiselect.value());
                $("#filter_form_action").val("filter");
                $("#filter_form").submit();
            });


            $("#checkbox_select_all").change(function () {
                if (this.checked)
                    $(".checkbox_selected_id").prop("checked", true);
                else
                    $(".checkbox_selected_id").prop("checked", false);
            });

            // User clicked reject
            $("#actionButton_approve").click(function () {
                $("#approval_form #actionButton").val(this.value);
                $("#confirmationModal").modal('show');
            });

            $("#actionButton_reject").click(function () {
                $("#approval_form #actionButton").val(this.value);
                $("#rejectionModal").modal('show');
            });
            $("#rejectionModal_OK").click(function () {
                
                var multiselect = $("#filter_entryowner").data("kendoMultiSelect");
                $("#approval_form #filter_entries").val(multiselect.value());

                $("#approval_form #rejection_reason").val(
                    $("#rejectionModal #rejection_reason_entry").val());
                $("#approval_form").submit();
            });

            $("#confirmationModal_OK").click(function () {
                var multiselect = $("#filter_entryowner").data("kendoMultiSelect");
                $("#approval_form #filter_entries").val(multiselect.value());
                $("#approval_form").submit();
            });

        });

    }(jQuery));

    </script>
}
